package cn.bupt.adt.controller;

import cn.bupt.adt.constant.Constants;
import cn.bupt.adt.entity.autogenerate.Carousel;
import cn.bupt.adt.service.ICarouselService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/carouselManagement")
public class CarouselController {

    @Autowired
    ICarouselService carouselService;

    @RequestMapping("/index/{pageNum}")
    public ModelAndView index(@PathVariable("pageNum") int pageNum) {
        ModelAndView mv = new ModelAndView(Constants.CAROUSELS_INDEX);
        Page<?> page = PageHelper.startPage(pageNum, Constants.PAGESIZE, "");
        List<Carousel> carousels = carouselService.getAllCarousels();
        mv.addObject("carousels", carousels);
        mv.addObject("allPages", page.getPages());
        mv.addObject("currentPage", page.getPageNum());
        return mv;
    }

    @RequestMapping("/modifyCarousel/{id}")
    public ModelAndView modify(@PathVariable("id") int id) {
        ModelAndView mv = new ModelAndView(Constants.CAROUSELS_MODIFY);
        mv.addObject("id", id);
        return mv;
    }

    @RequestMapping("/modifyPost/{id}")
    public ModelAndView modifyPost(@PathVariable("id") int id, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("forward:/carouselManagement/index/1");
        String oper_message = null;
        if (carouselService.modifyCarousel(request, id))
            oper_message = "修改成功";
        else
            oper_message = "修改失败！";
        mv.addObject("oper_message", oper_message);
        return mv;
    }
}
